<template>
  <div class="cart">
    <h2 class="cart-title">购物车</h2>
    <div class="cart-table">
      <el-table
        :data="tableData"
        style="width: 100%"
        :row-class-name="tableRowClassName"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column prop="images" label="商品图片">
          <template slot-scope="scope">
            <img :src="scope.row.images" class="cart-item-image" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="商品名称"></el-table-column>
        <el-table-column prop="price" label="单价"></el-table-column>
        <el-table-column prop="goodsNum" label="数量" align="center">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.goodsNum"
              :min="1"
              :max="10"
              size="mini"
              @change="handleCountChange(scope.row, scope.row.goodsNum)"
            ></el-input-number>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="cart-total">
      <div class="cart-total-text">已选 {{ selected.length }} 件商品</div>
      <div class="cart-total-price">总金额：{{ totalPrice }}</div>
      <el-button type="primary">结算</el-button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: [],
      selected: [],
    };
  },
  computed: {
    totalPrice() {
      return this.selected.reduce((total, item) => {
        return total + item.price * item.goodsNum;
      }, 0);
    },
  },
  created() {
    this.show();
  },
  methods: {
    show() {
      this.axios
        .get(
          "http://localhost:48543/api/Shop/GetShopCar?uid=" +
            localStorage.getItem("uid")
        )
        .then((res) => {
          this.tableData = res.data;
        });
    },
    handleSelectionChange(val) {
      this.selected = val;
    },
    tableRowClassName({ row }) {
      if (this.selected.includes(row)) {
        return "cart-table-row--selected";
      }
      return "";
    },
    handleCountChange(row, count) {
      row.count = count;
    },
    formatPrice(row) {
      return `￥${(row.price * row.count).toFixed(2)}`;
    },
  },
};
</script>

<style>
.cart-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}
.cart-item-image {
  width: 64px;
  height: 64px;
  object-fit: cover;
}
.cart-table-row--selected {
  background-color: #f5f5f5;
}
.cart-total {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.cart-total-text {
  font-size: 14px;
}
.cart-total-price {
  font-size: 18px;
  font-weight: bold;
}
</style>